package com.hsyg.netty.client;

import com.hsyg.netty.client.handler.ClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 客户端
 */
public class Client {

  /**
   * @param args
   * @throws Exception
   */
  public static void main(String[] args) throws Exception {
    int port = 8888;

    if (null != args && args.length > 0) {
      try {
        port = Integer.valueOf(args[0]);

      } catch (Exception e) {
        e.printStackTrace();

      }
    }

    new Client().connect("localhost", port);

  }

  /**
   * @param host
   * @param port
   * @throws Exception
   */
  public void connect(String host, int port) throws Exception {
    //配置线程组
    EventLoopGroup group = new NioEventLoopGroup();

    try {
      //客户端启动辅助类Bootstrap
      Bootstrap bootstrap = new Bootstrap();
      bootstrap.group(group)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new ClientHandler());
          }
        });

      //发起异步连接操作
      ChannelFuture future = bootstrap.connect(host, port).sync();

      //等待客户端链路关闭
      future.channel().closeFuture().sync();

    } finally {
      //优雅退出，释放nio线程组
      group.shutdownGracefully();
    }
  }

}
